//
//  YTTCopyLabel.swift
//  YTTTools
//
//  Created by AndyCui on 2018/8/30.
//  Copyright © 2018年 AndyCuiYTT. All rights reserved.
//

import UIKit

class YTTCopyLabel: UILabel {
    
    @IBInspectable
    var selectedColor: UIColor?
    
    private var oldeBackgroundColor: UIColor?
   
    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    private func setup() {
        self.isUserInteractionEnabled = true
        let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        self.addGestureRecognizer(longPressGestureRecognizer)
        NotificationCenter.default.addObserver(self, selector: #selector(showMenuController(_:)), name: UIMenuController.willShowMenuNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(hideMenuController(_:)), name: UIMenuController.willHideMenuNotification, object: nil)
    }
    
    @objc private func showMenuController(_ notification: Notification) {
        if self.isFirstResponder, let color = selectedColor {
            oldeBackgroundColor = self.backgroundColor
            self.backgroundColor = color
        }
    }
    
    @objc private func hideMenuController(_ notification: Notification) {
        if self.isFirstResponder, let _ = selectedColor {
            self.backgroundColor = oldeBackgroundColor
        }
    }
    
    @objc private func longPressAction(_ sender: UIGestureRecognizer) {
        
        guard sender.state == .began else {
            return
        }
        
        // 变为第一响应者
        self.becomeFirstResponder()
        
        // 菜单控制器
        let menuController = UIMenuController.shared
        // 复制 item
        let copyItem = UIMenuItem(title: "复制", action: #selector(copyText))
        // 添加 item 到 menu 控制器
        menuController.menuItems = [copyItem]
        // 设置菜单控制器点击区域为当前控件 bounds
        menuController.setTargetRect(self.bounds, in: self)
        // 菜单显示器可见
        menuController.setMenuVisible(true, animated: true)
        
    }
    
    @objc private func copyText() {
        UIPasteboard.general.string = self.text
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(copyText) {
            return true
        }
        return false
    }
    
    override var canBecomeFirstResponder: Bool { return true }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}
